package com.withoutwords.engine.settings;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.SharedPreferences;

import com.withoutwords.engine.MyInfo;
import com.withoutwords.engine.social.SocialUser;

public class Settings {

	SharedPreferences mPrefs;
	MyInfo me;
	String pushToken = "";

	public String getPushToken() {
		if(pushToken.isEmpty())
		{
			if (mPrefs != null) 
				pushToken = mPrefs.getString("pushToken", "");
		}
		return pushToken;
	}

	public void setPushToken(String pushtoken) {
		if (!pushToken.equals(pushtoken)) {
			this.pushToken = pushtoken;
			SharedPreferences.Editor editor = mPrefs.edit();
			editor.putString("pushToken", pushToken);

			editor.commit();
		}
	}

	private Settings() {

	}

	static Settings mSettingsInstance;

	public static Settings getInstance() {
		if (mSettingsInstance == null)
			mSettingsInstance = new Settings();
		return mSettingsInstance;
	}

	public void setPrefrences(SharedPreferences prefs) {
		mPrefs = prefs;
	}

	public String getCurrentUserId() {
		try {
			return getMyInfo().getUserId();
		} catch (NullPointerException e) {
			return "";
		}
	}

	public void setMyInfo(String myId, SocialUser mySocialInfo, String myEmail,
			boolean bSaveToPrefrences) {
		me = new MyInfo();
		me.setEmail(myEmail);
		me.setSocialUser(mySocialInfo);
		me.setUserId(myId);
		setMyInfo(me, bSaveToPrefrences);
	}

	public MyInfo getMyInfo() {
		if (me == null) {

			if (mPrefs != null) {
				String meJsonString = mPrefs.getString("me", "");
				try {
					JSONObject meJsonObj = new JSONObject(meJsonString);
					me = new MyInfo();
					me.fromJSON(meJsonObj);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return me;
	}

	public void setMyInfo(MyInfo me, boolean bSaveToPrefrences) {
		this.me = me;
		if (bSaveToPrefrences) {
			if (mPrefs != null) {
				SharedPreferences.Editor editor = mPrefs.edit();
				editor.putString("me", me.toJSON().toString());

				editor.commit();
			}
		}

	}

}
